import { loginByUsername, logout } from '@/api/login'
import { getPermissions } from '@/api/permission'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

const jwtDecode = require('jwt-decode')
const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    permissions: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          if (response.code === '118000001') {
            Message({ message: response.msg, type: 'error', duration: 5 * 1000 })
            reject('error')
          } else {
            commit('SET_TOKEN', response.data)
            setToken(response.data)
            resolve()
          }
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        const data = jwtDecode(state.token)
        const roleList = data.userRoleList
        const appRoleList = []
        for (let a = 0; a < roleList.length; a++) {
          if (roleList[a].appCode === process.env.APP_CODE) {
            appRoleList.push(roleList[a])
          }
        }
        data.userRoleList = appRoleList
        this.dispatch('_SetUserInfoState', data)
        resolve()
      })
    },

    // 获取用户权限信息
    GetPermissions({ commit, state }) {
      return new Promise((resolve, reject) => {
        getPermissions().then(response => {
          const data = response.data
          this.dispatch('_SetPermissions', data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 同时获取用户信息和用户权限信息
    GetUserInfoAndPermissions({ commit, state }) {
      return Promise.all([this.dispatch('GetUserInfo'), this.dispatch('GetPermissions')])
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 设置用户信息
    _SetUserInfoState: function({ commit, state }, data) {
      const userName = data.realName || data.nickname || data.account
      commit('SET_NAME', userName)
      commit('SET_AVATAR', data.avatar)
      commit('SET_INTRODUCTION', data.userId)
      commit('SET_ROLES', data.userRoleList)
    },

    // 设置权限
    _SetPermissions: function({ commit, state }, data) {
      commit('SET_PERMISSIONS', data)
    }

  }
}

export default user
